package cn.graydove.bot.adapter;

import cn.graydove.bot.exception.NoSuchMessageException;
import cn.graydove.bot.mirai.Client;
import net.mamoe.mirai.contact.Group;
import net.mamoe.mirai.contact.Member;
import net.mamoe.mirai.message.data.At;
import net.mamoe.mirai.message.data.Image;
import net.mamoe.mirai.message.data.Message;
import net.mamoe.mirai.message.data.MessageChainBuilder;

import java.util.Optional;

public class RobotClient {

    private Client client;

    public Client getClient() {
        return client;
    }

    public RobotClient(Client client) {
        this.client = client;
    }

    public GroupMessageEvent getGroupMemberInfo(Long groupNumber, long userId) {
        Optional<Group> group = Optional.of(client.getBot()).map(bot -> bot.getGroup(groupNumber));

        Optional<Member> member = group.map(groups -> groups.getOrNull(userId));

        if (member.isEmpty()) {
            return null;
        }
        return new GroupMessageEvent(new Client(client.getBot(), member.get(), client.getMessage(), group.get(), client.getProperties()));
    }

    public void sendGroupMsg(Long groupId, String message) {
        client.sendMessage(message);
    }

    public void sendGroupMsg(Long groupId, MessageChainBuilder message) {
        client.sendMessage(message);
    }

    public At getAt() {
        for (Message msg : client.getMessage()) {
            if (msg instanceof At) {
                return (At) msg;
            }
        }
        return null;
    }

    public Long getNumber() {
        String number = client.findNumber(client.getMessage().contentToString());
        if (number == null) {
            return null;
        }
        try {
            return Long.parseLong(number);
        } catch (Exception e) {
            return null;
        }
    }
}
